package com.gym.core.common;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

public class IPUtils {
    /**
     * 获取用户真实IP
     */
    public static String getUserRealIP(HttpServletRequest request) {
        // 公司统一用X-Real-IP
        String userIp = request.getHeader("X-Real-IP");
        if (notExists(userIp)){
            // 这是一个可以伪造的头
            userIp = request.getHeader("X-Forwarded-For");
            if (notExists(userIp)){
                userIp = request.getRemoteAddr();
            }
        }

        // 最后一个为RemoteAddr
        int pos = userIp.lastIndexOf(',');
        if (pos >= 0) {
            userIp = userIp.substring(pos);
        }
        if ("0:0:0:0:0:0:0:1".equals(userIp)) {
            userIp = "127.0.0.1";
        }
        return userIp;
    }

    public static boolean notExists(String userIp){
        return StringUtils.isBlank(userIp) || StringUtils.equalsIgnoreCase(userIp, "unknown");
    }
}
